<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of controller
 *
 * @author phamhphuc
 */

class referer_action_controller extends system_controller {    
    public function indexAction()
    {        
        if($this->config['facebookstatus'] && isset($this->config['facebookstatus']['app_data'])) {
            $this->_forward("register");
        }
    }
    
    public function tosAction(){
        $this->_setNoLayout();
    }
    
    public function aboutAction()
    {
        
    }
    
    public function registerAction()
    {
        $error = "";
//        if($this->_isLogined()){
//            header("location: ?action=index");die;
//        }
        
        $isInvited = false;
        
        if($this->session->refer_by_id) {
            $invitedID = $this->session->refer_invited_id;
            $inviteData = $this->db->getRow("select * from #__invite_friend where invite_friend_id = {$invitedID}");
            $this->view->inviteData = $inviteData;
            $isInvited = true;
            
            $inviterData = $this->db->getRow("select * from #__user where user_id = {$this->session->refer_by_id}");
            $this->view->inviterData = $inviterData;
        }
        
        if(isset($_POST['data'])){
            $data = $_POST['data'];
            if($data['password'] != $data['retype_password']) {
                $error = "Password does not match<br/>";
            } else {
                unset($data['retype_password']);
                $data['password'] = md5($data['password']);
            }

            $user = $this->db->getRow("select * from #__user where email = {$data['email']}");
            if($user) {
                $error = "Email already exist<br/>";
            }
            
            // check and update refer by id           
            if($this->session->refer_by_id) {
                // set refer by id for new user
                $data['refer_by_id'] = $this->session->refer_by_id;
                // update number of refers for refer user
                
                $numberOfRefer = $this->db->getOne("select count(*) from #__user where refer_by_id = {$data['refer_by_id']}");
                $numberOfRefer++;
                
                $updateReferSQL = "
                    update #__user set num_of_referers = {$numberOfRefer} where user_id = {$data['refer_by_id']}
                    ";                
                $this->db->query($updateReferSQL);
            }            
            if($error == "") {                
                $data['created_date'] = date("Y-m-d H:i:s");
                $this->db->insert("#__user", $data);
                header("location: ?action=login");
            }
        }
        
        $this->view->isInvited = $isInvited;
    }

    public function loginAction()
    {
        if($this->_isLogined()) {
            header("location: ?action=index");die;
        }
        if(isset($_POST['data'])){
            $data = $_POST['data'];
            $sql = "select * from #__user where email = '{$data['email']}' and password = md5('{$data['password']}')";
            $user = $this->db->getRow($sql);
            if($user) {
                $this->session->user = $user;
                $this->db->update("#__user", array(
                    "last_login" => date("Y-m-d H:i:s")
                ),"email = '{$user['email']}'");
                header("location: ?action=index");die;
            }
        }
    }
    
    public function addtabAction(){
        $this->_setNoLayout();
    }
    
    public function inviteAction(){
        $invited = false;
        $names = array();
        $uids = array();
        
        if(isset($_POST['data'])) {
            $data = $_POST['data'];
            if($data['uids'] == "" || $data['names'] == "" || $data['user_text'] == "") {
                $this->view->error = "Du må velge hvilke venner du vil sende invitasjonen til og skrive inn en personlig hilsen";
            } else {
                $user = $this->_getCurrentUser(false);
                if(!$user) {
                    $this->view->error = "Out of session!!!";
                    return;
                }
                
                $accessToken = $user['facebook_access_token'];
                $facebook = $this->_getFacebookObject();                
                                
                $names = explode(", ", $data['names']);                                
                $uids = explode(", ", $data['uids']);
                
                $userText = $data['user_text'];                               
                                
                $facebook->setAccessToken($accessToken);
                
                foreach($uids as $k => $f) {
                    if($f) {
                        
                        // insert to database to save the invation
                        $inviteDetail = array(
                            'fb_user_id' => $f,
                            'fb_username' => $names[$k],
                            'invite_date' => date("Y-m-d H:i:s"),
                            'invited_by_id' => $user['user_id'],
                            'message' => $userText
                        );
                        $invitedID = $this->db->insert("#__invite_friend", $inviteDetail);
//                        
//                        print_r($invitedID);die;
//                        $invitedID = 1;
                        try {                            
                            $args = array(                                
                                    'message' => $userText,
                                    'link' => $this->config['lightbox_like_url'] . "&app_data={$user['user_id']}_{$f}_{$invitedID}",
                                    'picture' => "http://ssl.socialmediatoolbox.no/fbreferer/templates/birken/assets/img/birkebeiner.jpg",
                                    'name' => "Delta i Birkebeinerløpet",
                                    'description' => "Hei {$names[$k]}, Birkebeinerløpet er et fantastisk arrangement og jeg anbefaler deg å ta en titt, kanskje deltakelse er noe for deg?"
                                );
                            
                            $facebook->api("/{$f}/feed","post", $args);
                        } catch(FacebookApiException $e) {
                            // get out of loop
//                            print_r($e);
                            break;
                        }                        
                    }                                        
                }
                $invited = true;
            }
        }        
        $this->view->invited = $invited;
        $this->view->names = $names;
        $this->view->uids = $uids;
    }
    
    public function fblikeviewAction()
    {
        
        if(isset($_GET['app_data'])) {
            
            $appdatas = explode("_", $_GET['app_data']);
            
            $refererID = $appdatas[0];
            $referToID = 0;
            $invitedID = 0;
            
            if(isset($appdatas[1])){
                $referToID = $appdatas[1];
            }
            
            if(isset($appdatas[2])){
                $invitedID = $appdatas[2];
            }
            
            // update clicks
            $updateClicksSQL = "update #__user set num_of_clicks = num_of_clicks + 1 where user_id = {$refererID}";
            $this->db->query($updateClicksSQL);
            
            // update invite clicks
            $updateInviteClicksSQL = "update #__invite_friend set num_of_clicks = num_of_clicks + 1 where invite_friend_id = {$invitedID}";
            $this->db->query($updateInviteClicksSQL);
            
            // write down the referer to session            
            $this->session->refer_by_id = $refererID;
            $this->session->refer_to_id = $referToID;
            $this->session->refer_invited_id = $invitedID;
            
            $url = $this->config['facebooktab_share_url'] . "?app_data={$refererID}";
            header("location: {$url}");die;
        }
        
        $this->_setNoLayout();
    }
    
    public function logoutAction()
    {
        $this->session->user = false;
        header("location: ?action=index");
    }

    public function loginfacebookAction()
    {
        $this->_setNoLayout();
        $userID = $_POST['userID'];
        $accessToken = $_POST['accessToken'];

        // get big profile picture
        $facebook = $this->_getFacebookObject();
        $facebook->setAccessToken($accessToken);

        $fbuser = $facebook->api('/me', array(
                          'fields' => 'picture, first_name, last_name, name, email, birthday, gender, hometown',
                          'type'   => 'large'
                      ));

        $hometown = "";

        if($fbuser['hometown']) {
            $hometown = $fbuser['hometown']['name'];
        }

        $bigPicture     = $fbuser['picture'];
        
        if(isset($bigPicture['data'])){
            $bigPicture = $bigPicture['data']['url'];
        }        

        $birthday = "";
        if($fbuser['birthday']) {
            $birthdays = explode("/", $fbuser['birthday']);
            $birthday = "{$birthdays[2]}-{$birthdays[0]}-{$birthdays[1]}";
        }

        // check if have user with this email
        $sql = "select * from #__user where email = '{$fbuser['email']}'";
        
        $user = $this->db->getRow($sql);

        if($user){
            if($user['facebook_user_id'] == "") {
                $this->db->update("#__user", array(
                   "facebook_user_id"  => $fbuser['id'],
                   "facebook_user_picture" => $bigPicture,
                   "facebook_access_token" => $accessToken,
                   'birthday' => $birthday,
                   'gender' => $fbuser['gender'],
                    'hometown' => $hometown,
                   "last_login" => date("Y-m-d H:i:s")
                ),"email = '{$fbuser['email']}'");
            } else {
                $this->db->update("#__user", array(
                    "facebook_access_token" => $accessToken,
                    "facebook_user_picture" => $bigPicture,
                    'birthday' => $birthday,
                    'hometown' => $hometown,
                    "last_login" => date("Y-m-d H:i:s")
                ),"email = '{$fbuser['email']}'");
            }
        } else {
            
            // check and update refer by id           
            if($this->session->refer_by_id) {
                // set refer by id for new user
                $data['refer_by_id'] = $this->session->refer_by_id;
                // update number of refers for refer user
                
                $numberOfRefer = $this->db->getOne("select count(*) from #__user where refer_by_id = {$data['refer_by_id']}");
                $numberOfRefer++;
                
                $updateReferSQL = "
                    update #__user set num_of_referers = {$numberOfRefer} where user_id = {$data['refer_by_id']}
                    ";                
                $this->db->query($updateReferSQL);
            }
            
            $data = array(
                'first_name' => $fbuser['first_name'],
                'last_name' => $fbuser['last_name'],
                'name' => $fbuser['name'],               
                'created_date' => date("Y-m-d H:i:s"),
                'email' => $fbuser['email'],
                'birthday' => $birthday,
                'gender' => $fbuser['gender'],
                'hometown' => $hometown,
                'facebook_user_data' => json_encode($fbuser),
                'facebook_user_picture' => $bigPicture,
                'facebook_access_token' => $accessToken,
                'facebook_user_id' => $fbuser['id'],
                'last_login' => date("Y-m-d H:i:s"),                
            );
            $this->db->insert("#__user", $data);

            $sql = "select * from #__user where email = '{$fbuser['email']}'";
            $user = $this->db->getRow($sql);
        }
        if($user) {
            // login this user
            $this->session->user = $user;
            echo json_encode(array(
                'status' => "1",
                'message' => "OK"
            ));
        }
    }

    private function _isLogined()
    {
        if($this->session->user) {
            return true;
        } else {
            return false;
        }
    }

    private function _getCurrentUser($useCache = true)
    {
        if(!$useCache) {
            $user = $this->session->user;
            $sql = "select * from #__user where user_id = {$user['user_id']}";
            $this->session->user = $this->db->getRow($sql);
        }
        return $this->session->user;

    }
    
    public function init()
    {
        parent::init();
        if($this->_isLogined()) {
            $user = $this->_getCurrentUser(false);
            if(!$user) {
                $this->session->user = false;
            } else {
                $this->view->user = $user;
                $this->view->isLogined = true;      
            }
        }      

        $this->view->isConnectedFacebook = $this->_isConnectedFacebook();
    }

    private function _isConnectedFacebook()
    {
        if($this->_isLogined()) {
            $user = $this->_getCurrentUser();
            if($user['facebook_user_id'] != "") {
                return true;
            }
        }
        return false;
    }
    
    private function _getFacebookObject()
    {
        require_once '../../libs/facebook/facebook.php';
        $facebook = new Facebook(array(
          'appId'  => $this->config['facebook_app_id'],
          'secret' => $this->config['facebook_app_secret'],
          'fileUpload' => true
        ));
        return $facebook;
    }
    
    public function getTemplateDir(){
        
        if($this->config['template_name']) {
            return "../../templates/{$this->config['template_name']}/";
        }
        return "";
    }
    
    public function getTemplateURL(){
        if($this->config['template_name']) {
            return "../../templates/{$this->config['template_name']}/";
        }
        return "";
    }
}

?>
